package com.bing.schoolmanager.Servlet;

import com.alibaba.fastjson2.JSON;
import com.bing.schoolmanager.pojo.Admin;
import com.bing.schoolmanager.pojo.ReturnData;
import com.bing.schoolmanager.service.AdminService;
import com.bing.schoolmanager.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String loginId = req.getParameter("loginId");
        String loginPwd = req.getParameter("loginPwd");

        AdminService adminService = new AdminServiceImpl();
        Admin admin = adminService.getAdminByLogin(loginId);
        ReturnData retData = null;
        if (admin != null) {
            if (admin.getLoginPwd().equals(loginPwd)) {
                String ckMe = req.getParameter("ckMe");

                Cookie cookie1 = new Cookie("loginId", loginId);
                Cookie cookie2 = new Cookie("loginPwd", loginPwd);
                Cookie cookie3 = new Cookie("ckMe", ckMe);
                if ("false".equals(ckMe)) {
                    cookie1.setMaxAge(0);
                    cookie2.setMaxAge(0);
                    cookie3.setMaxAge(0);
                }

                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
                resp.addCookie(cookie3);

                retData = ReturnData.success("登录成功", admin);
                req.getSession().setAttribute("admin", admin);

            } else {
                retData = ReturnData.error("密码错误!");
            }
        } else {
            retData = ReturnData.error("账号错误!");

        }
        resp.getWriter().write(JSON.toJSONString(retData));
    }
}
